package com.zenithmind.note.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.common.security.SecurityUtils;
import com.zenithmind.note.mapper.NoteTagRelationMapper;
import com.zenithmind.note.pojo.entity.NoteTagRelation;
import com.zenithmind.note.service.NoteTagRelationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 笔记标签关联服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class NoteTagRelationServiceImpl extends ServiceImpl<NoteTagRelationMapper, NoteTagRelation> implements NoteTagRelationService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setNoteTags(String noteId, List<String> tagIds) {
        // 先删除原有关联
        deleteByNoteId(noteId);
        
        // 如果没有新标签，直接返回
        if (CollectionUtils.isEmpty(tagIds)) {
            return;
        }
        
        // 创建新关联
        String currentUserId = SecurityUtils.getCurrentUserId();
        List<NoteTagRelation> relations = new ArrayList<>();
        
        for (String tagId : tagIds) {
            NoteTagRelation relation = new NoteTagRelation();
            relation.setNoteId(noteId);
            relation.setTagId(tagId);
            relation.setCreateBy(currentUserId);
            relation.setUpdateBy(currentUserId);
            relations.add(relation);
        }
        
        // 批量保存
        this.saveBatch(relations);
    }

    @Override
    public List<String> getTagIdsByNoteId(String noteId) {
        LambdaQueryWrapper<NoteTagRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NoteTagRelation::getNoteId, noteId)
                .select(NoteTagRelation::getTagId);
        
        return this.list(queryWrapper).stream()
                .map(NoteTagRelation::getTagId)
                .collect(Collectors.toList());
    }

    @Override
    public List<String> getNoteIdsByTagId(String tagId) {
        LambdaQueryWrapper<NoteTagRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NoteTagRelation::getTagId, tagId)
                .select(NoteTagRelation::getNoteId);
        
        return this.list(queryWrapper).stream()
                .map(NoteTagRelation::getNoteId)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByNoteId(String noteId) {
        LambdaQueryWrapper<NoteTagRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NoteTagRelation::getNoteId, noteId);
        this.remove(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByTagId(String tagId) {
        LambdaQueryWrapper<NoteTagRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NoteTagRelation::getTagId, tagId);
        this.remove(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addNoteTag(String noteId, String tagId) {
        // 检查关联是否已存在
        LambdaQueryWrapper<NoteTagRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NoteTagRelation::getNoteId, noteId)
                .eq(NoteTagRelation::getTagId, tagId);

        if (this.count(queryWrapper) > 0) {
            log.warn("笔记标签关联已存在：noteId={}, tagId={}", noteId, tagId);
            return;
        }

        // 创建新关联
        String currentUserId = SecurityUtils.getCurrentUserId();
        NoteTagRelation relation = new NoteTagRelation();
        relation.setNoteId(noteId);
        relation.setTagId(tagId);
        relation.setCreateBy(currentUserId);
        relation.setUpdateBy(currentUserId);

        this.save(relation);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeNoteTag(String noteId, String tagId) {
        LambdaQueryWrapper<NoteTagRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NoteTagRelation::getNoteId, noteId)
                .eq(NoteTagRelation::getTagId, tagId);

        this.remove(queryWrapper);
    }
}